package com.xhs.interceptor;

import org.apache.commons.io.IOUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @desc: 保存请求体参数的内容
 * @projectName: java-tools-parent
 * @author: xhs
 * @date: 2023-8-27 027 19:06
 * @version: JDK 1.8
 */
public class RequestWrapper extends HttpServletRequestWrapper {

    /**
     * 保存请求体参数
     */
    private final String body;
    /**
     * 保存其他类型的参数
     */
    private final Map<String, String[]> parameterMap;

    /**
     * 获取参数
     *
     * @param request request
     * @throws IOException IOException
     */
    public RequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        // 获取请求体参数
        body = IOUtils.toString(request.getInputStream(), StandardCharsets.UTF_8);
        // 获取其他类型的参数
        parameterMap = new HashMap<>(request.getParameterMap());
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes());
        return new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }

            @Override
            public int read() {
                return byteArrayInputStream.read();
            }
        };
    }

    @Override
    public String getParameter(String name) {
        String[] values = parameterMap.get(name);
        if (values != null && values.length > 0) {
            return values[0];
        }
        return null;
    }

    @Override
    public Map<String, String[]> getParameterMap() {
        return parameterMap;
    }

    @Override
    public Enumeration<String> getParameterNames() {
        return Collections.enumeration(parameterMap.keySet());
    }

    @Override
    public String[] getParameterValues(String name) {
        return parameterMap.get(name);
    }

    /**
     * 获取请求体参数
     *
     * @return String
     */
    public String getBody() {
        return body;
    }
}
